package com.commerce.product.config;

import com.commerce.common.constant.RabbitMQConstant;
import org.springframework.amqp.core.*;
import org.springframework.amqp.rabbit.config.SimpleRabbitListenerContainerFactory;
import org.springframework.amqp.rabbit.connection.ConnectionFactory;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.amqp.support.converter.Jackson2JsonMessageConverter;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.HashMap;
import java.util.Map;

/**
 * 秒杀系统RabbitMQ配置
 */
@Configuration
public class FlashSaleRabbitMQConfig {

    /**
     * 秒杀交换机
     */
    @Bean
    public DirectExchange flashSaleExchange() {
        return ExchangeBuilder
                .directExchange(RabbitMQConstant.FLASH_SALE_EXCHANGE)
                .durable(true)
                .build();
    }

    /**
     * 秒杀订单队列
     */
    @Bean
    public Queue flashSaleOrderQueue() {
        Map<String, Object> args = new HashMap<>();
        // 设置死信交换机
        args.put("x-dead-letter-exchange", RabbitMQConstant.FLASH_SALE_EXCHANGE);
        args.put("x-dead-letter-routing-key", "flash.sale.order.dlq");
        // 设置消息TTL（15分钟）
        args.put("x-message-ttl", RabbitMQConstant.FLASH_SALE_ORDER_TIMEOUT);
        
        return QueueBuilder
                .durable(RabbitMQConstant.FLASH_SALE_ORDER_QUEUE)
                .withArguments(args)
                .build();
    }

    /**
     * 秒杀订单死信队列
     */
    @Bean
    public Queue flashSaleOrderDlq() {
        return QueueBuilder
                .durable(RabbitMQConstant.FLASH_SALE_ORDER_DLQ)
                .build();
    }

    /**
     * 秒杀库存回滚队列
     */
    @Bean
    public Queue flashSaleStockRollbackQueue() {
        return QueueBuilder
                .durable(RabbitMQConstant.FLASH_SALE_STOCK_ROLLBACK_QUEUE)
                .build();
    }

    /**
     * 秒杀订单延迟队列（用于订单超时处理）
     */
    @Bean
    public Queue flashSaleOrderDelayQueue() {
        Map<String, Object> args = new HashMap<>();
        // 设置死信交换机，消息过期后转发到订单处理队列
        args.put("x-dead-letter-exchange", RabbitMQConstant.FLASH_SALE_EXCHANGE);
        args.put("x-dead-letter-routing-key", RabbitMQConstant.FLASH_SALE_ORDER_ROUTING_KEY);
        
        return QueueBuilder
                .durable(RabbitMQConstant.FLASH_SALE_ORDER_DELAY_QUEUE)
                .withArguments(args)
                .build();
    }

    /**
     * 绑定秒杀订单队列
     */
    @Bean
    public Binding bindingFlashSaleOrder() {
        return BindingBuilder
                .bind(flashSaleOrderQueue())
                .to(flashSaleExchange())
                .with(RabbitMQConstant.FLASH_SALE_ORDER_ROUTING_KEY);
    }

    /**
     * 绑定秒杀订单死信队列
     */
    @Bean
    public Binding bindingFlashSaleOrderDlq() {
        return BindingBuilder
                .bind(flashSaleOrderDlq())
                .to(flashSaleExchange())
                .with("flash.sale.order.dlq");
    }

    /**
     * 绑定秒杀库存回滚队列
     */
    @Bean
    public Binding bindingFlashSaleStockRollback() {
        return BindingBuilder
                .bind(flashSaleStockRollbackQueue())
                .to(flashSaleExchange())
                .with(RabbitMQConstant.FLASH_SALE_STOCK_ROLLBACK_ROUTING_KEY);
    }

    /**
     * 绑定秒杀订单延迟队列
     */
    @Bean
    public Binding bindingFlashSaleOrderDelay() {
        return BindingBuilder
                .bind(flashSaleOrderDelayQueue())
                .to(flashSaleExchange())
                .with(RabbitMQConstant.FLASH_SALE_ORDER_DELAY_ROUTING_KEY);
    }

    /**
     * JSON消息转换器
     */
    @Bean
    public Jackson2JsonMessageConverter flashSaleMessageConverter() {
        return new Jackson2JsonMessageConverter();
    }

    /**
     * RabbitTemplate配置
     */
    @Bean
    public RabbitTemplate flashSaleRabbitTemplate(ConnectionFactory connectionFactory) {
        RabbitTemplate template = new RabbitTemplate(connectionFactory);
        template.setMessageConverter(flashSaleMessageConverter());
        
        // 设置发送确认
        template.setConfirmCallback((correlationData, ack, cause) -> {
            if (!ack) {
                System.err.println("秒杀消息发送失败：" + cause);
            }
        });
        
        // 设置返回确认
        template.setReturnsCallback(returned -> {
            System.err.println("秒杀消息被退回：" + returned.getMessage());
        });
        
        return template;
    }

    /**
     * 监听器容器工厂配置
     */
    @Bean
    public SimpleRabbitListenerContainerFactory flashSaleRabbitListenerContainerFactory(
            ConnectionFactory connectionFactory) {
        SimpleRabbitListenerContainerFactory factory = new SimpleRabbitListenerContainerFactory();
        factory.setConnectionFactory(connectionFactory);
        factory.setMessageConverter(flashSaleMessageConverter());
        
        // 设置并发消费者数量
        factory.setConcurrentConsumers(3);
        factory.setMaxConcurrentConsumers(10);
        
        // 设置预取数量
        factory.setPrefetchCount(1);
        
        // 设置确认模式
        factory.setAcknowledgeMode(AcknowledgeMode.MANUAL);
        
        // 设置重试机制
        factory.setDefaultRequeueRejected(false);
        
        return factory;
    }
}
